package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.config.DongDongSearchConfig;
import com.dongdongshop.pojo.goods.TbGoods;
import com.dongdongshop.pojo.item.TbItem;
import com.dongdongshop.service.GoodsServiceI;
import com.dongdongshop.util.PageInfo;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;

import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("es")
public class ESController {

    private final Logger logger= LoggerFactory.getLogger(ESController.class);

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Reference
    private GoodsServiceI goodsServiceI;

    @RequestMapping("toSearch")
    public String toES(String autocomplete, Model model){
        model.addAttribute("autocomplete",autocomplete);
        return "search";
    }


    @RequestMapping("searchItem")
    @ResponseBody
    public PageInfo searchItem(String autocomplete, @RequestParam(defaultValue = "1")Integer pageNumber){
        System.out.println("进入方法"+autocomplete);
        PageInfo<TbItem> page = new PageInfo<>();
        page.setPageNumber(pageNumber);
        page.setPageSize(2);
        page.setOffset(1);

        List<TbItem> list = new ArrayList<>();
        // 创建检索请求
        SearchRequest searchRequest = new SearchRequest();
        //指定索引
        searchRequest.indices("dongdongshop");
        //指定DSL检索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("title",autocomplete));
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        HighlightBuilder.Field highlightTitle =new HighlightBuilder.Field("title");
        searchSourceBuilder.from(0+(pageNumber-1)*2);
        searchSourceBuilder.size(2);
        highlightTitle.preTags("<span style='color:red'>");
        highlightTitle.postTags("</span>");
        highlightBuilder.field(highlightTitle);
        searchSourceBuilder.highlighter(highlightBuilder);
        System.out.println(">>>检索条件 : " + searchSourceBuilder);

        searchRequest.source(searchSourceBuilder);
        //执行检索
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, DongDongSearchConfig.COMMON_OPTIONS);
            //分析结果
            System.out.println(">>>返回结果" + search.toString());
            page.setTotal(search.getHits().getTotalHits());
            SearchHits hits = search.getHits();
            SearchHit[] innerHis = hits.getHits();
            for (SearchHit hit : innerHis) {
                // 获取高亮内容
                String sourceAsStringOfUser = hit.getSourceAsString();
                ObjectMapper objectMapper = new ObjectMapper();
                TbItem item = objectMapper.readValue(sourceAsStringOfUser, TbItem.class);
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                for (Text title : titles) {
                    item.setTitle(title.toString());
//                    System.out.println("高亮"+title.toString());
                }
                list.add(item);

            }
            page.setList(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return page;
    }

    @Scheduled(cron = "0 0 4 * * ?")
    public void insertES() throws IOException {
        List<TbGoods> tbGoods=goodsServiceI.getGoodsAll();
        for (TbGoods goods : tbGoods) {
            //执行
            IndexRequest indexRequest = new IndexRequest("dongdongshop", "goods");
            String goodsJson = new ObjectMapper().writeValueAsString(goods);
            indexRequest.source(goodsJson, XContentType.JSON);

            // indexRequest.source(goods);
            IndexResponse response = restHighLevelClient.index(indexRequest, DongDongSearchConfig.COMMON_OPTIONS);
            //提取有用的响应信息
            System.out.println(">>>index: "+response);
        }

    }
}
